package cn.leonis.leetcode;

import java.util.Arrays;

/**
 * @author Tobi
 * @time 2021-12-09 11:47 PM
 * leetcode283
 * 移动元素0，将0移动到数组的末尾
 */
public class MoveZeroSolution {

    public static void main(String[] args) {
        int[] nums = {0, 1};
        MoveZeroSolution solution = new MoveZeroSolution();
        solution.moveZeroes(nums);
        Arrays.stream(nums).forEach(System.out::println);
    }

    /**
     * 解法一：双指针
     * @param nums
     */
    public void moveZeroes(int[] nums) {
        int len = nums.length, left = 0, right = 0;
        while (right < len) {
            if (nums[right] != 0) {
                // swap(nums, left, right);
                // 使用位运算，当元素只有一位的时候，会出现错误
                nums[right] = nums[left] ^ nums[right];
                nums[left] = nums[left] ^ nums[right];
                nums[right] = nums[left] ^ nums[right];
                left++;
            }
            right++;
        }
    }

    /**
     * 交换
     * @param nums
     * @param left
     * @param right
     */
    public void swap(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}
